﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace MadProps.Templating
{
    class SelfTemplatingImpl
    {
        readonly List<ITemplateSuggestor> suggestors;
        readonly IProp prop;

        internal SelfTemplatingImpl(Composition composition, IProp prop)
        {
            this.suggestors = composition.ThrowIfNull("composition")
                .ResolveAll<ITemplateSuggestor>().ToList();

            this.prop = prop.ThrowIfNull("prop");
        }

        internal DataTemplate SelectTemplate(Control target)
        {
            var args = new TemplateSuggestionArgs(target, prop);

            foreach (var suggestor in suggestors)
            {
                suggestor.SuggestTemplates(args);
            }

            foreach (var suggestion in args.ResourceSuggestions)
            {
                var template = target.TryFindResource(suggestion) as DataTemplate;
                if (template != null)
                {
                    return template;
                }
            }

            return null;
        }
    }
}
